<template>
  <Dialog v-model="dialogVisible" title="审核" width="50%" draggable="true">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品" prop="relId" label-width="60">
            <el-select v-model="formData.relId" placeholder="请选择产品" @change="relIdChange" style="width: 70%">
              <el-option
                v-for="dict in coalTypeList"
                :key="dict.id"
                :label="dict.proName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="卸货地址" prop="adressId" label-width="80">
            <el-select v-model="formData.adressId" placeholder="请选择卸货地址" style="width: 70%">
              <el-option
                v-for="dict in unloadingAddressList"
                :key="dict.id"
                :label="dict.cusAddress"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <ContentItemWrap v-if="showBiddingContent && cardList.length !== 0">
      <template #title>竞价派车包</template>
      <template #content>
        <div class="selected-card-info">
          <div class="info-item">
            <span class="label">时间：</span>
            <span class="value">{{ selectedCardInfo.timeRange }}</span>
          </div>
          <div class="info-item" style="margin-left: 10px;">
            <span class="label">预估剩余量：</span>
            <span class="value">{{ selectedCardInfo.forecastSurplusAmount}}吨</span>
          </div>
        </div>
        <div class="hint-row">
          <img src="@/assets/imgs/hint.png" alt="hint" class="hint-icon"/>
          <span class="hint-text">请选择下方竞价派车单进行派单</span>
        </div>
        <div class="card-container-wrapper">
          <div class="card-container">
            <div
              v-for="card in cardList"
              :key="card.id"
              :class="['card-item', { selected: selectedCardId === card.id }]"
              @click="selectCard(card.id)"
            >
              <div class="card-content">
                <div class="card-row">
                  <span class="card-label">时间:</span>
                  <span class="card-value">{{ card.startTime }} 至 {{ card.endTime }}</span>
                </div>
                <div class="card-row">
                  <span class="card-label">编号:</span>
                  <span class="card-value">{{ card.biddingNo }}</span>
                </div>
                <div class="card-row">
                  <span class="card-label">预估剩余量:</span>
                  <span class="card-value red-text">{{ parseFloat(card.forecastSurplusAmount).toFixed(2) }}吨</span>
                </div>
                <div class="progress-bar">
                  <el-progress
                    :text-inside="false"
                    :stroke-width="20"
                    :percentage="calculatePercentage(card.transportAmount, card.planValue)"
                    :show-text="false"
                    style="flex: 1;"
                  />
                  <span class="progress-text">
                    {{ calculatePercentage(card.transportAmount, card.planValue) }}%
                  </span>
                </div>
              </div>
              <!-- 选中角标 -->
              <div v-if="selectedCardId === card.id" class="card-badge">
                <img src="@/assets/imgs/checked.png" alt="checked" class="badge-icon"/>
              </div>
            </div>
          </div>
        </div>
        <el-form-item prop="selectedCardId" style="display: none;">
          <el-input v-model="selectedCardId" style="display: none;"/>
        </el-form-item>
      </template>
    </ContentItemWrap>
    <template #footer>
      <el-button :disabled="loading" @click="auditCanceForm">审核作废</el-button>
      <el-button :disabled="formLoading" type="primary" @click="auditPassForm">审核通过</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import {listSimpleJLDictData} from "@/api/system/dict/dict.data";
import * as salesWaybillApi from "@/api/salesWaybill";
import * as salesPlanApi from "@/api/salesPlan";

const formRef = ref()
const {t} = useI18n()
const message = useMessage()
const dialogTitle = ref('')
const formLoading = ref(false)
const loading = ref(false)
const dialogVisible = ref(false)
const emit = defineEmits(['success'])
const formData: Record<string, any> = ref({
  id: undefined,
  cusId: undefined,
  relId: undefined,
  adressId: undefined,
  dataSource: undefined,
  status: undefined,
  outTenantId: undefined,
  proId: undefined,
  batchId: undefined,
})

const selectedCardInfo = ref({
  timeRange: '',
  forecastSurplusAmount: ''
})

const formRules = reactive({
  relId: [{required: true, message: '审核的产品不能为空', trigger: 'change'}],
  adressId: [{required: true, message: '审核的卸货地址不能为空', trigger: 'change'}],
})

const coalTypeList = ref([])
const getCoalTypeList = async () => {
  const res = await salesWaybillApi.findProCusRelName({cusId: formData.value.cusId})
  coalTypeList.value = res || []
}
const unloadingAddressList = ref([])
const getUnloadingAddressList = async () => {
  const res = await salesWaybillApi.findcusAddressbyCusId({cusId: formData.value.cusId})
  unloadingAddressList.value = res || []
}
const cardList = ref([])
const selectedCardId = ref(null)
// 初始化时选中第一个卡片（如果只有一个卡片则默认选中）
watch(cardList, (newList) => {
    if (newList.length === 1) {
      // 只有一个卡片时默认选中
        selectedCardId.value = newList[0].id;
        formData.value.batchId = newList[0].batchId;

      selectedCardInfo.value = {
        timeRange: formatCardTime(newList[0].startTime, newList[0].endTime),
        forecastSurplusAmount: newList[0].forecastSurplusAmount
      };

    } else if (newList.length > 1 && selectedCardId.value === null) {
      // 多个卡片且未选中任何卡片，则不默认选中
      selectedCardId.value = null;
      formData.value.batchId = undefined;
    } else if (newList.length === 0) {
      // 无卡片时清空选中和 batchId
      selectedCardId.value = null;
      formData.value.batchId = undefined;
    }
}, {immediate: true})


// 卡片点击事件
const selectCard = (id) => {
  selectedCardId.value = id;
  const selectedCard = cardList.value.find(card => card.id === id);
  if (selectedCard) {
    formData.value.batchId = selectedCard.batchId;

    selectedCardInfo.value = {
      timeRange: formatCardTime(selectedCard.startTime, selectedCard.endTime),
      forecastSurplusAmount: selectedCard.forecastSurplusAmount
    };
  }
}

/** 打开弹窗 */
const dataSourceList = ref([])
const open = async (id: number, cusId: String, tenantId: number) => {
  resetFn()
  dialogVisible.value = true
  showBiddingContent.value = false
  selectedCardId.value = null
  formData.value.id = id
  const resjl = await listSimpleJLDictData()
  dataSourceList.value = resjl.filter((item) => {
    return item.dictType == 'req_system_source'
  })
  formData.value.dataSource = dataSourceList.value[1].value
  formData.value.cusId = cusId
  formData.value.outTenantId = tenantId
  getCoalTypeList()
  getUnloadingAddressList()
  await getBiddingConfig()
}
const showBiddingContent = ref(false)
const showBiddingValue = ref(null)
const getBiddingConfig = async () => {
  try {
    const res = await salesWaybillApi.findBiddingConfigbyOutTenantId({outTenantId: formData.value.outTenantId})
    showBiddingValue.value = res.percentageOfPerformance
    showBiddingValue.value = 90
  } catch (error) {
    showBiddingValue.value = null
  }
}

const relIdChange = (selectedId) => {
  const selectedItem = coalTypeList.value.find(item => item.id === selectedId);
  if (selectedItem && selectedItem.proId) {
    formData.value.proId = selectedItem.proId;
  }
  selectedCardInfo.value = {
    timeRange: undefined,
    forecastSurplusAmount: undefined
  }
  if (showBiddingValue.value != null && showBiddingValue.value != undefined) {
    showBiddingContent.value = true
    getBiddingPackageData()
  } else {
    showBiddingContent.value = false
  }
}
// 添加获取竞价包数据
const getBiddingPackageData = async () => {
  if (!showBiddingContent.value || !formData.value.proId) {
    return
  }
  try {
    const res = await salesWaybillApi.getBiddingPackageData({
      cusId: formData.value.cusId,
      proId: formData.value.proId,
      enterId: formData.value.outTenantId
    })
    if (res.code === 0 && res.data) {
      cardList.value = res.data || []
    }
  } catch (error) {
    message.error('获取竞价包数据失败')
  }
}

const calculatePercentage = (transportAmount, planValue) => {
  if (!transportAmount || !planValue) return 0;
  const percentage = (transportAmount / planValue) * 100;
  return Math.min(100, Math.max(0, Number(percentage.toFixed(2))));
}

// 添加时间格式化方法
const formatCardTime = (startTime, endTime) => {
  if (!startTime || !endTime) return '';
  const startDate = startTime.split(' ')[0];
  const endDate = endTime.split(' ')[0];
  return `${startDate}至${endDate}`;
};

const router = useRouter()
// 审核通过
const auditPassForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (showBiddingContent.value && cardList.value.length > 0 && !selectedCardId.value) {
    message.error('请选择竞价派车包')
    return
  }
  formData.value.status = 1
  try {
    formLoading.value = true
    const res = await salesWaybillApi.saleWaybillAudit(formData.value)
    if (res.code === 0) {
      message.success(t('common.operateSuccess'))
      dialogVisible.value = false
      resetFn()
      emit('success')
    } else if (res.code === 100910003) {
      await message.confirm(res.msg)
      refreshAuthorize()
    } else if (res.code === 100910004) {
      await message.confirm(res.msg)
      router.push({path: '/authManageCatalog/authorizationManage'})
    } else {
      message.error(res.msg)
    }
  } finally {
    formLoading.value = false
  }
}
const refreshAuthorize = async () => {
  await salesPlanApi.refreshAuthorize()
}
// 审核作废
const auditCanceForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formData.value.status = 2
  try {
    loading.value = true
    const res = await salesWaybillApi.saleWaybillAudit(formData.value)
    if (res.code === 0) {
      message.success(t('common.operateSuccess'))
      dialogVisible.value = false
      resetFn()
      emit('success')
    } else if (res.code === 100910003) {
      await message.confirm(res.msg)
      refreshAuthorize()
    } else if (res.code === 100910004) {
      await message.confirm(res.msg)
      router.push({path: '/authManageCatalog/authorizationManage'})
    } else {
      message.error(res.msg)
    }
  } finally {
    loading.value = false
  }
}
const resetFn = () => {
  formData.value = {
    id: undefined,
    cusId: undefined,
    relId: undefined,
    adressId: undefined,
    dataSource: undefined,
    status: undefined,
  }
  selectedCardInfo.value = {
    timeRange: undefined,
    forecastSurplusAmount: undefined
  };
  formRef.value?.resetFields()
}
defineExpose({open}) // 提供 open 方法
</script>
<style lang="scss" scoped>
.card {
  background: rgba(64, 158, 254, 0.08);
  border-radius: 4px;
  padding: 16px 0;
  text-align: center;

  .label {
    font-size: 14px;
    font-family: "PingFang SC", "PingFang SC-400";
    font-weight: 400;
    text-align: center;
    color: #606266;
    line-height: 22px;
  }

  .value {
    font-size: 14px;
    font-family: "PingFang SC", "PingFang SC-500";
    font-weight: 500;
    text-align: center;
    color: #303133;
    line-height: 22px;
    margin-top: 8px;
  }
}
.hint-row {
  margin-top: 10px;
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  .hint-icon {
    margin-right: 8px;
    width: 20px;
    height: 20px;
  }

  .hint-text {
    font-size: 14px;
    font-family: "PingFang SC", "PingFang SC-400";
    font-weight: 400;
    text-align: left;
    color: #f3a73f;
    line-height: 22px;
  }
}
.card-container-wrapper {
  max-height: 400px; /* 设置固定高度 */
  overflow-y: auto;  /* 超出时显示垂直滚动条 */
  margin-top: 10px;
}
.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.card-item {
  position: relative;
  flex: 0 0 calc(50% - 10px);
  background: #ffffff;
  border: 1px solid #EDEDED;
  border-radius: 4px;
  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.08);
  padding: 16px;
  cursor: pointer;

  &.selected {
    border-color: #409EFE;
    border-width: 2px;
  }

  &:not(.selected) {
    border-color: #EDEDED;
  }

  &:only-child {
    cursor: not-allowed;
  }
}

.card-content {
  .card-row {
    display: flex;
    margin-bottom: 8px;
  }

  .card-label, .card-value {
    font-size: 13px;
    font-family: "PingFang SC", "PingFang SC-400";
    font-weight: 400;
    text-align: left;
    color: #3a3a3a;
    line-height: 22px;
  }

  .card-label {
    width: 80px;
    flex-shrink: 0;
  }

  .red-text {
    color: red;
  }
}

.progress-bar {
  margin-top: 10px;
  display: flex;
  align-items: center;

  .progress-text {
    color: #409EFF;
    font-size: 13px;
    font-weight: 500;
    margin-left: 10px;
    white-space: nowrap;
  }
}
.card-badge {
  position: absolute;
  top: -1px;
  right: -1px;

  .badge-icon {
    width: 50px;
    height: 50px;
  }
}
.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.selected-card-info {
  background: rgba(64, 158, 254, 0.08);
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  margin-top: 10px;

  .info-item {
    display: flex;
    align-items: center;

    .label {
      font-size: 14px;
      font-family: "PingFang SC", "PingFang SC-400";
      font-weight: 400;
      color: #606266;
      line-height: 22px;
      white-space: nowrap;
      margin-left: 10px;
    }

    .value {
      font-size: 14px;
      font-family: "PingFang SC", "PingFang SC-500";
      font-weight: 500;
      text-align: center;
      color: #303133;
      line-height: 22px;
      margin-left: 8px;
    }
  }
}
</style>
